//
//  ZCTakeCarSearchViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/16.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCTakeCarSearchViewController.h"
#import "ZCTaskListTableViewCell.h"
#import "ZCTakeCarDetailViewController.h"
#import "ZCTaskModel.h"
#import "ZCTakeCarSearchTableViewCell.h"

//static NSString *taskListCell = @"ZCTaskListTableViewCell";
static NSString *taskListCell = @"ZCTakeCarSearchTableViewCell";

@interface ZCTakeCarSearchViewController ()<UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *taskArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, strong) ZCTaskPageInfoModel *pageInfoModel;
@property (nonatomic, strong) MBProgressHUD *hud;
@end

@implementation ZCTakeCarSearchViewController
#pragma mark - 懒加载
- (NSMutableArray *)taskArray {
    if (!_taskArray) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, SCREENHEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = ZCColor(0xf7f8fb, 1);
        
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        
//        [_tableView registerClass:[ZCTaskListTableViewCell class] forCellReuseIdentifier:taskListCell];
        [_tableView registerClass:[ZCTakeCarSearchTableViewCell class] forCellReuseIdentifier:taskListCell];
        
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        _tableView.mj_footer.automaticallyHidden = YES;
        
    }
    return _tableView;
}
- (UISearchBar *)searchBar {
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
        _searchBar.placeholder = @"输入订单号/车架号";
        _searchBar.delegate = self;
        _searchBar.keyboardType = UIKeyboardTypeASCIICapable;
    }
    return _searchBar;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tabBarController.tabBar.hidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, space(522), 30)];
    [titleView addSubview:self.searchBar];
    self.navigationItem.titleView = titleView;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
    UIButton *rightButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [rightButton setTitle:@"取消" forState:UIControlStateNormal];
    [rightButton setTitleColor:ZCColor(0x000000, 0.87) forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(30)];
    [rightButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.page = 1;
    [self.view addSubview:self.tableView];
    
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.searchBar.text.length > 0) {
        [self.hud showAnimated:YES];
        [self loadNewData];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if (self.queryParam.length == 0) {
        [self.searchBar becomeFirstResponder];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (self.hud) {
         [self.hud hideAnimated:YES];
        self.hud.mode = MBProgressHUDModeIndeterminate;
    }
}

#pragma mark - 属性方法
- (void)setQueryParam:(NSString *)queryParam {
    _queryParam = queryParam;
    self.searchBar.text = queryParam;
    [self.hud showAnimated:YES];
    [self loadNewData];
}

#pragma mark - 按钮点击
- (void)backToHome {
    [self.searchBar resignFirstResponder];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [searchBar resignFirstResponder];
    [self.hud showAnimated:YES];
    [self loadNewData];
}

#pragma mark - 网络请求
- (void)loadNewData {
    [self loadDataWithTaskType:0];
}

- (void)loadDataWithTaskType:(NSInteger)type {
    self.page = 1;
    __weak typeof(self)weakSelf = self;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.searchBar.text forKey:@"queryParam"];
    [params setObject:@(self.page) forKey:@"pageNo"];
    [params setObject:@(10) forKey:@"pageSize"];
    NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
    if (originId.length > 0) {
        [params setObject:originId forKey:@"pointId"];
    }
    if (self.taskType > 0) {
        [params setObject:@(self.taskType) forKey:@"taskType"];
    }
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        [ZCHttpTool postWithURL:HomeSearch params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                [weakSelf.taskArray removeAllObjects];
                NSArray *dataArray = responseObject[@"data"];
                for (NSDictionary *dic in dataArray) {
                    ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                    [weakSelf.taskArray addObject:taskModel];
                }
                weakSelf.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:responseObject[@"pageVo"]];
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf.tableView reloadData];
                if (dataArray.count < 10) {
                    [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                }else {
                    [weakSelf.tableView.mj_footer resetNoMoreData];
                }
            }else {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf.hud showAnimated:YES];
                    weakSelf.hud.mode = MBProgressHUDModeText;
                    weakSelf.hud.label.text = responseObject[@"message"];
                    [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                });
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            [weakSelf.tableView.mj_header endRefreshing];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.hud showAnimated:YES];
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = error.localizedDescription;
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            });
        }];
    });
    
}

- (void)loadMoreData {
    
    [self loadMoreDataWithTaskType:0];
}

- (void)loadMoreDataWithTaskType:(NSInteger)type {
    self.page++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:self.searchBar.text forKey:@"queryParam"];
    [params setObject:@(self.page) forKey:@"pageNo"];
    [params setObject:@(10) forKey:@"pageSize"];
    NSString *originId = [[NSUserDefaults standardUserDefaults] objectForKey:UserOriginId];
    if (originId.length > 0) {
        [params setObject:originId forKey:@"pointId"];
    }
    if (self.taskType > 0) {
        [params setObject:@(self.taskType) forKey:@"taskType"];
    }
    
    __weak typeof(self)weakSelf = self;
    if (self.page <= [self.pageInfoModel.totalPage integerValue]) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            [ZCHttpTool postWithURL:HomeSearch params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"success"] boolValue]) {
                    NSArray *dataArray = responseObject[@"data"];
                    for (NSDictionary *dic in dataArray) {
                        ZCTaskModel *taskModel = [ZCTaskModel yy_modelWithDictionary:dic];
                        [weakSelf.taskArray addObject:taskModel];
                    }
                    self.pageInfoModel = [ZCTaskPageInfoModel yy_modelWithDictionary:responseObject[@"pageVo"]];
                    [weakSelf.tableView reloadData];
                    if (dataArray.count < 10) {
                        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                    }else {
                        [weakSelf.tableView.mj_footer endRefreshing];
                    }
                }else {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [weakSelf.hud showAnimated:YES];
                        weakSelf.hud.mode = MBProgressHUDModeText;
                        weakSelf.hud.label.text = responseObject[@"message"];
                        [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
                    });
                }
                
            } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                self.page--;
                [weakSelf.tableView.mj_footer endRefreshing];
            }];
        });
    }else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.taskArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ZCTakeCarSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:taskListCell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section];
    cell.taskModel = taskModel;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(351);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return space(20);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ZCTaskModel *taskModel = (ZCTaskModel *)self.taskArray[indexPath.section];
    if ([taskModel.taskType integerValue] != 0) {
        ZCTakeCarDetailViewController *detailVC = [[ZCTakeCarDetailViewController alloc] init];
        detailVC.taskId = taskModel.taskId;
        detailVC.taskType = taskModel.taskType;
        detailVC.fromSearch = YES;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}
@end
